package com.dc.free.util;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.StrKit;

/**
 * response格式    data数据可以用MapUtil生成，
 * @author quan
 *
 */
public class StatusUtil {
	
	private Map<String, Object> status = new HashMap<String, Object>();
	private Map<String, Object> data = null;
	public static final Integer ERROR = -1;
	public static final Integer SUCCESS = 0;
	/**
	 * 全局返回码
	 * @author quan
	 * @since 2017-09-05
	 * @version 0.1
	 */
	private static final Map<Integer, String> codeMsg = new HashMap<Integer, String>();
	
	static {
		codeMsg.put(-1, "系统繁忙");
		codeMsg.put(0, "成功");
        
		codeMsg.put(100000, "验证码错误");
		codeMsg.put(100001, "姓名或工号错误");
		codeMsg.put(100002, "竞价失败");
		codeMsg.put(100003, "活动未开始");
		codeMsg.put(100004, "活动已结束");
		codeMsg.put(111111, "重新登录");
	}
	
	/**
     * 通过返回码获取返回信息
     * @param errCode 错误码
     * @return {String}
     */
    public static String getMsg(int code){
        String result = codeMsg.get(code);
        return result != null ? result : "未知返回码：" + code;
    }
	
	public static StatusUtil create() {
		return new StatusUtil();
	}
	
	public static StatusUtil create(String key, String value) {
		return new StatusUtil(key, value);
	}
	
	public static StatusUtil create(int code, String stack, Object _data) {
		return create(code, null, stack, _data);
	}
	
	public static StatusUtil create(int code, String msg, String stack, Object _data) {
		StatusUtil su = new StatusUtil();
		String codeMsg = getMsg(code);
		
		su.putStatus("code", code+"")
		  .putStatus("msg", StrKit.notBlank(msg) ? msg : codeMsg)
		  .putStatus("stack", stack)
		  .putStatus("data", su.data != null ? su.data : _data);
		return su;
	}
	
	public StatusUtil() {}
	
	public StatusUtil(String key, Object value) {
		status.put(key, value);
	}
	
	public StatusUtil putStatus(String key, Object value) {
		status.put(key, value);
		return this;
	}
	
	public StatusUtil putDate(String key, String value) {
		if(data == null) data = new HashMap<String, Object>();
		
		data.put(key, value);
		return this;
	}
	
	public Map<String, Object> getStatus() {
		return status;
	}
	
}
